package cn.milai.amtc.step4;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.milai.amtc.Audio;

/**
 * 使用单独线程池播放所有音频 -> 每个线程负责一个音频播放，可以同时播放的音频数量受限于线程池大小
 */
@SuppressWarnings("unchecked")
public class AudioManager {

	private static final int THREAD_NUM = 2;
	private static ExecutorService threadPool;
	private static Queue<Audio>[] audios;
	private static int index;

	static {
		index = 0;
		threadPool = Executors.newFixedThreadPool(THREAD_NUM);
		audios = new ConcurrentLinkedQueue[2];
		for (int i = 0; i < THREAD_NUM; i++) {
			audios[i] = new ConcurrentLinkedQueue<>();
		}
	}

	public static void add(Audio audio) {
		index = (index + 1) % THREAD_NUM;
		audios[index++].add(audio);
	}

	public static void play() {
		for (int i = 0; i < THREAD_NUM; i++) {
			for (Audio a : audios[i]) {
				threadPool.execute(a::play);
				audios[i].remove(a);
			}
		}
	}
}
